package com.handu.luna.core.domain.promotion;

import com.handu.luna.core.domain.user.User;
import com.handu.luna.core.domain.user.UserRank;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import javax.persistence.Entity;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by wangzailiang on 2014/7/2 .
 */
@Entity
public class CashCard extends Bonus {


    private String password;
    private BigDecimal leftPrice;


    /**
     * 通过现金卡类型ID查询所有现金卡(分页)
     * @param cashCardPromotionId
     * @param pageable
     * @return
     */
    public Page<CashCard> findAllByCashCardPromotionId(Long cashCardPromotionId,Pageable pageable) {
        Page<CashCard> page = context.getCashCardRepository().findAllByBonusPromotionId(cashCardPromotionId, pageable);
        List<CashCard> list = page.getContent();
        for(CashCard cashCard : list) {
            cashCard.init();
        }
        return page;
    }

    /**
     * 通过现金卡类型ID查询所有现金卡
     * @param cashCardPromotionId
     * @return
     */
    public List<CashCard> findAllByCashCardPromotionId(Long cashCardPromotionId) {
        List<CashCard> list = context.getCashCardRepository().findAllByBonusPromotionId(cashCardPromotionId);
        for(CashCard cashCard : list) {
            cashCard.init();
        }
        return list;
    }

    /**
     * 现金卡Excel导出
     * @param cashCardPromotionId
     * @return
     */
    public HSSFWorkbook getExcelModel(Long cashCardPromotionId) {

        List<CashCard> cashCardList = new CashCard().findAllByCashCardPromotionId(cashCardPromotionId);

        HSSFWorkbook wb = new HSSFWorkbook();
        int sheetCount = cashCardList.size()/60000 + 1;
        int beginIndex = 0;
        int endIndex = sheetCount > 1 ? 60000 : cashCardList.size();

        for (int sheetNum = 1; sheetNum <= sheetCount; sheetNum++) {

            HSSFSheet sheet = wb.createSheet("现金卡"+(sheetCount > 1 ? sheetNum :""));
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("现金卡卡号");
            headerRow.createCell(1).setCellValue("现金卡密码");
            headerRow.createCell(2).setCellValue("现金卡金额");
            headerRow.createCell(3).setCellValue("现金卡余额");
            headerRow.createCell(4).setCellValue("类型名称");
            headerRow.createCell(5).setCellValue("使用结束日期");

            for(int i=beginIndex,j=0; i<endIndex; i++,j++) {
                CashCard cashCard = cashCardList.get(i);

                Row row = sheet.createRow(j+1);
                row.createCell(0).setCellValue(cashCard.getCode());
                row.createCell(1).setCellValue(cashCard.getPassword());
                row.createCell(2).setCellValue(cashCard.getBonusPromotion().getBonusPrice().toString());
                row.createCell(3).setCellValue(cashCard.getLeftPrice().toString());
                row.createCell(4).setCellValue(cashCard.getBonusPromotion().getName());

                String strDate = "";
                if(cashCard.getBonusPromotion().getUseEndDate() != null) {
                    strDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cashCard.getBonusPromotion().getUseEndDate());
                }
                row.createCell(5).setCellValue(strDate);
            }

            beginIndex = 60000 * sheetNum;
            endIndex = sheetCount > (sheetNum+1) ? 60000*(sheetNum + 1) : cashCardList.size();
        }

        return wb;

    }

    public void delete(Long id,Long cashCardPromotionId) {
        CashCard cashCard = context.getCashCardRepository().findOne(id);
        CashCardPromotion cashCardPromotion = context.getCashCardPromotionRepository().findOne(cashCardPromotionId);
        cashCardPromotion.updateGrantNum(cashCardPromotionId, -1L);
        if(StringUtils.isNotBlank(cashCard.getOrderId())) {
            cashCardPromotion.updateUsedNum(cashCardPromotionId,-1L);
        }
        context.getCashCardRepository().delete(id);
    }

    /**
     * 生成序列号
     */
    public void generateCode() {
        StringBuilder prefix= new StringBuilder("HDJK");
        String code = prefix.append(System.nanoTime()).toString();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        setPassword(uuid.substring(0,15));
        setCode(code.substring(0,15));
    }

    /**
     * 初始化现金卡类型数据
     */
    public void init() {
        this.setBonusPromotion(context.getCashCardPromotionRepository().findOne(bonusPromotionId));
        if(userId != null) {
            this.setUser(context.getUserRepository().findOne(userId));
        }
    }

    public CashCard save(CashCard cashCard) {
        cashCard.generateCode();
        context.getCashCardRepository().save(cashCard);
        return cashCard;
    }


    public String getSucessFlashMessage(String message){
        String messagePrefix = (null==this.getId() ?"添加" : "修改");
        return messagePrefix + message + "成功";
    }

    public CashCard() {

    }

    public CashCard(String code, Long userId, String orderId, Date usedDate, Long bonusPromotionId) {
        super(code,userId,orderId,usedDate);
        this.bonusPromotionId = bonusPromotionId;
    }


    /**
     * 根据类型ID 和发放数量 发放
     * @param cashCardPromotionId
     * @param grantNum
     */
    public void save(Long cashCardPromotionId, Long grantNum) {

        CashCardPromotion cashCardPromotion = context.getCashCardPromotionRepository().findOne(cashCardPromotionId);

        for(int i=0; i<grantNum; i++) {
            CashCard cashCard = new CashCard();
            cashCard.setBonusPromotionId(cashCardPromotionId);
            cashCard.setLeftPrice(cashCardPromotion.getBonusPrice());
            this.save(cashCard);
        }

        new CashCardPromotion().updateGrantNum(cashCardPromotionId, grantNum);
    }

    public Long saveByUserRankId(Long userRankId,Long cashCardPromotionId) {

        UserRank userRank = context.getUserRankRepository().findOne(userRankId);
        List<User> userList;
        if(userRank.getIsSpecial()) {
            userList = context.getUserRepository().findByUserRank(String.valueOf(userRank.getId()));
        }else {
            userList = context.getUserRepository().findbyLevelPoint((int)userRank.getMinRank(),(int)userRank.getMaxRank());
        }
        CashCardPromotion cashCardPromotion = context.getCashCardPromotionRepository().findOne(cashCardPromotionId);
        long grantNum = 0L;

        for(User user : userList) {
            CashCard cashCard = new CashCard();
            cashCard.generateCode();
            cashCard.setBonusPromotionId(cashCardPromotionId);
            cashCard.setUserId(user.getId());
            cashCard.setLeftPrice(cashCardPromotion.getBonusPrice());
            this.save(cashCard);
            grantNum++;
        }

        new CashCardPromotion().updateGrantNum(cashCardPromotionId, grantNum);

        return grantNum;
    }

    public Long saveByUsersId(List<Long> userIds, Long cashCardPromotionId) {

        CashCardPromotion cashCardPromotion = context.getCashCardPromotionRepository().findOne(cashCardPromotionId);
        long grantNum = 0L;

        for(Long id: userIds) {
            CashCard cashCard = new CashCard();
            cashCard.generateCode();
            cashCard.setBonusPromotionId(cashCardPromotionId);
            cashCard.setUserId(id);
            cashCard.setLeftPrice(cashCardPromotion.getBonusPrice());
            this.save(cashCard);
            grantNum++;
        }

        new CashCardPromotion().updateGrantNum(cashCardPromotionId, grantNum);

        return grantNum;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public BigDecimal getLeftPrice() {
        return leftPrice;
    }

    public void setLeftPrice(BigDecimal leftPrice) {
        this.leftPrice = leftPrice;
    }
}
